package com.salesmanager.web.populator.catalog;


import com.salesmanager.core.business.category.model.Category;
import com.salesmanager.core.business.generic.exception.ConversionException;
import com.salesmanager.core.utils.AbstractDataPopulator;
import com.salesmanager.web.entity.catalog.category.ReadableCategory;
import com.salesmanager.web.utils.ImageFilePathUtils;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.LazyInitializationException;

import javax.servlet.http.HttpServletRequest;

public class ReadableCategoryPopulator extends
        AbstractDataPopulator<Category, ReadableCategory> {

    private HttpServletRequest request;

	@Override
	public ReadableCategory populate(Category source, ReadableCategory target) throws ConversionException {

        Validate.notNull(request, "Requires to set HttpServletRequest");

        target.setLineage(source.getLineage());

        target.setName(source.getName());
        target.setTitle(source.getTitle());
        target.setDescription(source.getDescription());
        target.setMetatagKeywords(source.getMetatagKeywords());

        try{
            if (source.getCategories() != null && source.getCategories().size() > 0){
                StringBuilder childBuild = new StringBuilder();
                for (Category category : source.getCategories()){
                    childBuild.append(category.getName()).append(",");
                }
                target.setChildrenStr(childBuild.substring(0,childBuild.length()-1));
            }
        }catch (LazyInitializationException e){

        }

		
		target.setCode(source.getCode());
		target.setId(source.getId());
		target.setVisible(source.isVisible());
        target.setSortOrder(source.getSortOrder());
        target.setCategoryStatus(source.getCategoryStatus());

        //image
        if (!StringUtils.isBlank(source.getCategoryImage())){
            target.setImage(ImageFilePathUtils.buildAppImageFilePath(source.getCode(), source.getCategoryImage(), request));
        }

		return target;
	}

	@Override
	protected ReadableCategory createTarget() {
		return null;
	}

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }
}
